import React, { useContext } from "react";
import { createUseStyles } from "react-jss";
import { ThemeContext } from "../../theme";
import { useErrmsgStyles } from "./styles";
import { isEmpty } from "@ct0/functions";
import Button from "../../Button";

const useStyles = createUseStyles({
  input: {
    borderRadius: "4px",
    border: "1px solid #D9D9D9",
    fontSize: (props: { fontSize: number }) => props.fontSize,
    color: "#333",
    padding: "3px 5px",
    "&::placeholder": {
      fontSize: "1em",
    },
    "&:hover": { borderColor: "#0B71BB" },
    "&:focus-visible": { borderColor: "#0B71BB", outline: 0 },
  },
  close: {
    display: "inline-block",
    border: "50%",
    width: "20px",
    height: "20px",
    textAlign: "center",
    lineHeight: "20px",
    cursor: "pointer",
    margin: "0 3px",
  },
});

export default function ArrayInputComponent({
  value: propsValue,
  type,
  disabled,
  errmsg,
  onChange,
}: {
  value?: Array<string | number>;
  type: "string" | "number";
  disabled?: boolean;
  errmsg?: string;
  onChange: (v: Array<string | number>) => void;
}) {
  const { fontSize } = useContext(ThemeContext);
  const classes = useStyles({ fontSize });
  const errClasses = useErrmsgStyles();
  const value = isEmpty(propsValue) ? [""] : propsValue!;

  const handler = (index: number, v: string | number = "") => {
    const values = value?.map((i, indexOrder) => {
      if (indexOrder == index) return type == "number" ? Number(v) : v;
      return type == "number" && i !== "" ? Number(i) : i;
    });
    onChange(values || []);
  };

  const add = () => onChange([...value, ""]);

  const remove = (index: number) => {
    const values: Array<string | number> = [];
    if (!value) return;
    for (let i = 0; i < value?.length; i++)
      if (i != index) values.push(value[i]);
    onChange(values);
  };

  return (
    <>
      <div>
        {value.map((i, index) => {
          return (
            <div key={index} style={{ display: "inline-block" }}>
              <input
                type={type}
                className={classes.input}
                value={i}
                onChange={(e) => handler(index, e.target.value)}
                disabled={disabled}
              />
              <div className={classes.close} onClick={() => remove(index)}>
                &times;
              </div>
            </div>
          );
        })}
        <Button onClick={add}>添加</Button>
      </div>
      {errmsg && <div className={errClasses.errmsg}>{errmsg}</div>}
    </>
  );
}
